﻿using System;
using System.Collections;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace LevelUp.Serializer.Test
{
    [TestClass]
	public class DataContractSerializerTest
    {
		#region Const
		const string SERIALIZE_FILE_NAME = @"SerializedData.dat";
		#endregion

		[TestMethod]
		[ExpectedException(typeof(ArgumentNullException))]
		public void Serialize_SerializeToNullStream_ThrowsArgumentNullException()
		{
			ISerializer serializer = new DataContractSerializer();
			serializer.Serialize(0, null as Stream);
		}

		[TestMethod]
		[ExpectedException(typeof(ArgumentException))]
		public void Serialize_SerializeToUnWritableStream_ThrowsArgumentException()
		{
			using (var ms = new MemoryStream(new byte[0],false))
			{
				ISerializer serializer = new DataContractSerializer();
				serializer.Serialize(0, ms);
			}
		}

		[TestMethod]
		public void DeSerialize_DeSerializeFromStream_DeSerializeSuccess()
		{
			using (var ms = new MemoryStream())
			{
				ISerializer serializer = new DataContractSerializer();
				serializer.Serialize(0, ms);

				ms.Seek(0, SeekOrigin.Begin);
				var result = serializer.DeSerialize<int>(ms);
				Assert.AreEqual(0, result);
			}
		}


		[TestMethod]
		public void Serialize_SerializeToStream_SerializeSuccess()
		{
			using (var ms = new MemoryStream())
			{
				ISerializer serializer = new DataContractSerializer();
				serializer.Serialize(0, ms);
				Assert.AreNotEqual(ms.Length, 0);
			}
		}



		[TestMethod]
		public void Serialize_SerializeObjToDataContractFile_SerializeSuccess()
		{
			//Arrange
			var obj = new ArrayList { "Larry", "LevelUp", @"http://www.dotblogs.com.tw/larrynung" };
		
			//Act
			ISerializer serializer = new DataContractSerializer();
			serializer.Serialize(obj, SERIALIZE_FILE_NAME);

			//Assert
			Assert.IsTrue(File.Exists(SERIALIZE_FILE_NAME), "Serialized file not existed");

			File.Delete(SERIALIZE_FILE_NAME);
		}

        [TestMethod]
        public void DeSerialize_DeSerializeObjFromDataContractFile_DeSerializeSuccess()
        {
            //Arrange
            var obj = new ArrayList { "Larry", "LevelUp", @"http://www.dotblogs.com.tw/larrynung" };
			var expectedObj = obj;

            //Act
			ISerializer serializer = new DataContractSerializer();
			serializer.Serialize(obj, SERIALIZE_FILE_NAME);
			var deSerializedObj = serializer.DeSerialize<ArrayList>(SERIALIZE_FILE_NAME);


            //Assert
			for (var idx = 0; idx < expectedObj.Count; ++idx)
			{
				Assert.AreEqual(expectedObj[idx], deSerializedObj[idx]);
			}

			File.Delete(SERIALIZE_FILE_NAME);
        }
    }
}
